package net.scdx.hotel.controller;


import net.scdx.hotel.dto.UserExecution;
import net.scdx.hotel.entity.User;
import net.scdx.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * user register
     */
    @PostMapping("/add")
    public String addUser(HttpServletRequest request, HttpServletResponse response){
        try {
            User user=new User();
            user.setUsername(request.getParameter("username"));
            user.setPassword(request.getParameter("password"));
            user.setCity(request.getParameter("city"));
            user.setDisplayName(request.getParameter("displayName"));
            user.setTel(request.getParameter("tel"));
            user.setGender(request.getParameter("gender"));

            UserExecution userExecution = userService.addUser(user);
            if (userExecution.isSuccess() == false) {
               // System.out.println("fail");
                request.setAttribute("registerFailure",true);
                request.setAttribute("msg",userExecution.getMsg());
                return "register";
            } else {
                // login successfully
                request.getRequestDispatcher("/").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "index";
    }



    /**
     * user login
     */
    @PostMapping("/login")
    public String userLogin(HttpServletRequest request, HttpServletResponse response) {
//        Map<String,Object> modelMap = new HashMap<>();
        try {
            // get request params
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            UserExecution userExecution = userService.userLogin(username, password);

            if (userExecution.isSuccess() == false) {
                request.setAttribute("loginFailure",true);
            } else {
                // login successfully
                request.getSession().setAttribute("user", userExecution.getUser());
            }

            request.getRequestDispatcher("/").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return "index";
    }

    /**
     * show user information
     */
    @GetMapping("/info")
    public Map<String,Object> getInfo(HttpSession session) {
        Map<String,Object> modelMap = new HashMap<>();
        User user = (User) session.getAttribute("user");

        try {
           if (user == null || user.getUsername() == null || (user = userService.userInfo(user.getUsername())) == null ) {
               modelMap.put("success", false);
               modelMap.put("msg", "session failure");
               return modelMap;
           }

            modelMap.put("success", true);
            modelMap.put("data", user);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return modelMap;
    }

    /**
     *  modify user info
     */
    @PostMapping("/modify")
    public String modifyInfo(User user, HttpServletRequest request, HttpServletResponse response) {
        try {
            User sessionUser = (User) request.getSession().getAttribute("user");

            if (sessionUser == null || sessionUser.getUsername() == null)
                request.getRequestDispatcher("/").forward(request, response);

            user.setUsername(sessionUser.getUsername());

            userService.midifyUser(user);

            request.getSession().setAttribute("user", user);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "info";
    }

    @GetMapping("/logout")
    @ResponseBody
    public Map<String,Object> userLogout(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<>();
        request.getSession().setAttribute("user", null);
        request.getSession().setAttribute("loginFailure",null);
        modelMap.put("success", true);

        //request.getSession().invalidate();
        return modelMap;
    }

    @PostMapping("/findpsw")
    @ResponseBody
    public Map<String,Object> userLogout(@RequestParam("username") String username, @RequestParam("verifycode") String verifycode, HttpSession httpSession) throws Exception {
        Map<String,Object> modelMap = new HashMap<>();
        modelMap.put("success", false);

        User member = userService.userInfo(username);
        if (member!=null && member.getUsername().equals(username) && httpSession.getAttribute("code").equals(verifycode)) {
            String password = member.getPassword();
            modelMap.put("success", true);
            modelMap.put("password", password);
        }

        return modelMap;
    }
    @RequestMapping("/list")
    public String usersPage(Model model, @RequestParam(value = "adminId", required = false) Integer adminId) {
        try{
            List<User> users = userService.usersInfo(adminId);
            model.addAttribute("users", users);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return "admin_users";
    }

    @RequestMapping("/delete")
    public String deletePage(Model model, @RequestParam(value = "userId", required = false) Integer userId) {
        try{
            userService.deleteUserById(userId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "admin";
    }

    @GetMapping("edit")
    public String editPage(Integer userId, Model model) {
        try{
            model.addAttribute("user", userService.findUserById(userId));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "editUser";
    }

    @PostMapping("/update")
    public String saveUser(User user){
        try{
            userService.saveUser(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "admin";
    }
}
